package com.tcu.base.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.tcu.user.entity.Token;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 定义jwt的工具类
 */
@Component
public class JwtUtil {

    // token过期时间
    @Value("mytoken.expire")
    public static  long EXPIRE =60*60*1000;
//    密钥，自己随机设置即可
    @Value("mytoken.secret")
    public static  String APP_SECRET ="smart_boiler_tcu";

    /**
     * 得到token字符串的方法
     * @param userId
     * @param username
     * @return
     */
    public static String getToken(String userId,String username){
        Date date = new Date(System.currentTimeMillis()+EXPIRE);
        Algorithm algorithm = Algorithm.HMAC256(APP_SECRET);//使用这种加密方式
        String token = JWT.create()
                .withClaim("userId",userId)
                .withClaim("username",username)
                .withExpiresAt(date)
                .sign(algorithm);
        return token;
    }

    /**
     * 进行token的验证,判断token是否 无效，过期，超时，加密算法不一致等。
     * @param token
     * @return
     */
    public static boolean verify(String token){
        if(! StringUtils.hasLength(token)){
            return false;
        }
        Token tokenInfo = getTokenInfo(token);
        try {
            Algorithm algorithm = Algorithm.HMAC256(APP_SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userId",tokenInfo.getUserId())
                    .withClaim("username",tokenInfo.getUsername())
                    .build();
            DecodedJWT jwt = verifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 解析token中的信息，能够得到Token对象
     * @param token
     * @return
     */
    public static Token getTokenInfo(String token){
        Token t = new Token();
        DecodedJWT decode = JWT.decode(token);


        try {
            t.setUserId(decode.getClaim("userId").asString());
            t.setUsername(decode.getClaim("username").asString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }


}
